package com.example.model_camerax

import android.util.Log
import android.util.Size
import android.view.Surface.ROTATION_0
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import com.example.common_base.ac.BaseAcKtBind
import com.example.model_camerax.databinding.ActivityCameraXactivityBinding
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class CameraXActivity : BaseAcKtBind<ActivityCameraXactivityBinding>() {
    private lateinit var mImageCapture: ImageCapture
    private lateinit var imageAnalyzer: ImageAnalysis
    private lateinit var cameraExecutor: ExecutorService

    override fun initSuc() {
        setUpCamera()
        //初始化线程池
        cameraExecutor = Executors.newSingleThreadExecutor();
    }

    private fun setUpCamera() {
//        初始化cameraProviderFuture并得到cameraProvider
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)


        cameraProviderFuture.addListener({
            //用于将相机的生命周期绑定到生命周期所有者
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            //在重新绑定之前取消绑定
            cameraProvider.unbindAll()
            //选择前置摄像头
            val cameraSelector =
                CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_FRONT).build()
            //创建预览
            val preview = Preview.Builder()
                .setTargetRotation(ROTATION_0)
                .build()


            //设置预览的View
            preview.setSurfaceProvider(binding.viewFinder.surfaceProvider)

//            //图像捕获
//            val imageCapture = ImageCapture.Builder()
//                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
//                .build();
            imageAnalyzer = ImageAnalysis.Builder()
                .setTargetResolution(Size(1280, 720))
                .build().also {
                    it.setAnalyzer(cameraExecutor, { image ->
                        Log.e("tag", "setUpCamera: ")
                        image.close()
                    })

                }


//            //创建图像捕捉
//            mImageCapture = ImageCapture.Builder().build()

            //将生命周期,选择摄像头,预览,绑定到相机
            cameraProvider.bindToLifecycle(this as LifecycleOwner,
                cameraSelector,
                imageAnalyzer, preview)
        }, ContextCompat.getMainExecutor(this))

    }
}